import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hkzf_flutter/scoped_model/auth_model.dart';
import 'package:hkzf_flutter/utils/common_toast.dart';
import 'package:hkzf_flutter/utils/dio_http.dart';
import 'package:hkzf_flutter/utils/public.dart';
import 'package:hkzf_flutter/utils/scoped_model_helper.dart';
import 'package:hkzf_flutter/utils/store.dart';

// 登录页面
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 是否展示密码
  bool showPassword = false;

  var userNameController = TextEditingController();
  var passwordController = TextEditingController();

  _loginHandler() async{
    var userName = userNameController.text;
    var password = passwordController.text;
    if(isNullOrEmpty(userName) || isNullOrEmpty(password)){
      CommonToast.showToast('用户名或密码不能为空');
      return;
    }
    // 登录参数
    var params = {
      "username": userName,
      "password": password
    };
    var path = '/user/login';
    var res =await DioHttp.of(context).post(path,params);
    var resMap = json.decode(res.toString());
    print('结果：${resMap}');

    int status = resMap['status'];
    String desc = resMap['description'] ?? '内部错误';
    // 展示接口提示信息
    CommonToast.showToast(desc);
    if(status.toString().startsWith('2')){
      // 登录成功，保存token信息，返回上一页
      String token = resMap['body']['token'];
      // 将token存储到本地（用于持久化）
      Store store= await Store.getInstance();
      store.setString(StoreKeys.token, token);

      // 将token保存到状态存储中(方便全局可以调用)
      ScopedModelHelper.getModel<AuthModel>(context).login(token, context);

      // 延迟1秒返回上一页
      Timer(Duration(seconds: 1),(){
        Navigator.of(context).pop();
        // Navigator.pop(context)
      });

    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("登录"),
        backgroundColor: Colors.green,
      ),
      body: SafeArea(
        minimum: const EdgeInsets.all(30),
        child: ListView(
          children: [
            TextField(
              controller: userNameController,
              decoration: const InputDecoration(labelText: '用户名', hintText: '请输入用户名'),
            ),
            const Padding(padding: EdgeInsets.all(10)),
            TextField(
              controller: passwordController,
              obscureText: !showPassword, //设置密码框显示为密文
              decoration: InputDecoration(
                  labelText: '密码',
                  hintText: '请输入密码',
                  suffixIcon: IconButton(
                    icon: showPassword
                        ? const Icon(Icons.visibility)
                        : const Icon(Icons.visibility_off),
                    onPressed: () => {
                      setState(() {
                        //showPassword取反，切换密文和明文
                        showPassword = !showPassword;
                      })
                    },
                  )),
            ),
            const Padding(padding: EdgeInsets.all(10)),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green, // 设置按钮颜色
                foregroundColor: Colors.white, // 设置按钮文字颜色
              ),
              onPressed: () => _loginHandler(),
              child: const Text("登录")
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center, //设置主轴居中对齐
              children: [
                const Text("还没有账号, "),
                TextButton(
                  child: const Text(
                    "去注册~",
                    style: TextStyle(
                      color: Colors.green, //设置字体颜色
                    ),
                  ),
                  onPressed: () {
                    // 点击跳转到注册页
                    Navigator.pushReplacementNamed(context, '/register');
                  }
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}
